package com.ayx.redispublish.Listener;

import com.ayx.redispublish.vo.MessageDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RedisMessageListener implements MessageListener {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        /**
         * 消息处理业务
         */
        //获取消息主体
        // 接收的topic
        log.info("channel:" + new String(pattern));
        MessageDto msg = (MessageDto) redisTemplate.getValueSerializer().deserialize(message.getBody());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            log.info("接收到来自redis推送的消息:{}",objectMapper.writeValueAsString(msg));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}
